<?php

namespace App\Http\Controllers\JsonApi;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Core\Enums\HeaderEnum;
use App\Api\Modules\User\AuthApi;
use App\Api\Requests\User\UserLogin;
use App\Repositories\UserLoginRepository;
use App\Http\Controllers\JsonApiController;

/**
 * 登陆接口
 * Class LoginController
 * @package App\Http\Controllers
 */
class LoginController extends JsonApiController implements AuthApi
{
    // token 默认配置过期时长
    protected const TokenExpireTimeCnfKv = 'auth.remember_token_timeout';

    /**
     * @inheritDoc
     */
    public function login(Request $request): Response
    {
        $data = new UserLogin($request);
        if (!$data->check()) {
            return $this->failed($data->validator()->errors()->first());
        }
        $result = (new UserLoginRepository())->login($data->username, $data->password);
        if ($result->code() == 200) {
            $key = strtolower(HeaderEnum::AuthToken);
            $token = $result->value($key);
            if (empty($data->remember)) {
                return $this->success($result->data());
            }
            return $this->success($result->data())->cookie(cookieItem($key, $token, self::TokenExpireTimeCnfKv));
        }
        return $this->failed($result->message());
    }

    /**
     * @inheritDoc
     */
    public function logout(Request $request): Response
    {
        $token = $request->header(HeaderEnum::AuthToken);
        if (empty($token)) {
            return $this->failed('注销异常');
        }
        $result = (new UserLoginRepository())->logout($token);
        if ($result->code() == 200) {
            return $this->success($result->toArray());
        }
        return $this->failed($result->message());
    }
}
